package com.moli.iov.handle.alarm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.moli.iov.base.enums.FenceAlarmTypeEnum;
import com.moli.iov.base.model.dto.res.VehicleBaseResDto;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.model.po.VehicleFence;
import com.moli.iov.base.remote.IVehicleBaseAuthRemoteService;
import com.moli.iov.base.remote.IVehicleBaseRemoteService;
import com.moli.iov.base.remote.IVehicleFenceRemoteService;
import com.moli.iov.handle.alarm.constants.Constant;
import com.moli.iov.handle.alarm.model.dto.AuthDto;
import com.moli.iov.handle.alarm.model.dto.VehicleBaseDto;
import com.moli.iov.handle.alarm.model.dto.VehicleFenceDto;
import com.moli.iov.handle.alarm.service.IAlarmOtherService;
import com.moli.iov.real.service.IRealService;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 调用 其它服务
 * </p>
 *
 * @author zql
 * @since 2019/9/27 15:45
 */
@Slf4j
@Service
public class AlarmOtherServiceImpl implements IAlarmOtherService {

  @Autowired
  private IVehicleBaseRemoteService vehicleBaseRemoteService;

  @Autowired
  private IVehicleBaseAuthRemoteService vehicleBaseAuthRemoteService;

  @Autowired
  private IRealService realService;

  @Autowired
  private IVehicleFenceRemoteService vehicleFenceRemoteService;

  /**
   * 查询基础服务
   * @param vin
   * @return
   */
  @Override
  public VehicleBaseDto queryVehicleBaseTbox(String vin) {

    VehicleBaseDto vehicleBaseDto = new VehicleBaseDto();
    try {
      RestResponse<VehicleBaseResDto> restResponse = vehicleBaseRemoteService
          .getVehicleCompanyIdByVin(vin);

      if(restResponse == null || !restResponse.flag){
        log.error("调用基础服务失败 返回空或失败 vin:{}", vin);
        return vehicleBaseDto;
      }

      log.info("查询基础服务 vin:{} 车辆基础数据：{}", vin, restResponse);


      CommonUtils.copyProperties(restResponse.getData(), vehicleBaseDto);
      return vehicleBaseDto;
    } catch (Exception e) {
      log.error("报警组装数据 调用基础服务异常", e);
      return vehicleBaseDto;
    }
  }

  /**
   * 查询上报时间
   * @param vin
   * @return
   */
  @Override
  public Date getRealTimeInfo(String vin) {
    try {

      RestResponse<Date> lastReportTime = realService.getLastReportTime(vin);
      log.info("查询上报时间 vin:{} lastReportTime:{}", vin, JSONObject.toJSONString(lastReportTime));
      if(lastReportTime == null || !lastReportTime.flag){
        return null;
      }

      return lastReportTime.getData();
    }catch(Exception e){
      log.error("实时服务 查询上报时间 异常", e);
      return null;
    }
  }

  /**
   * 查询车辆的围栏
   * @param vin
   * @return
   */
  @Override
  public Map<String, List<VehicleFenceDto>> listFencesByVin(String vin) {

    Map<String, List<VehicleFenceDto>> map = new HashMap<>();
    try{

      List<VehicleFence> vehicleFenceResDtos =
          vehicleFenceRemoteService.listVehicleFenceByVin(vin);
      if(vehicleFenceResDtos == null || vehicleFenceResDtos.isEmpty()){
        log.error("查询车辆围栏失败， 基础服务返回空 vin:{}", vin);
        return map;
      }
      log.info("查询车辆的围栏 vin:{} vehicleFenceResDtos：{}", vin, JSONObject.toJSONString(vehicleFenceResDtos));

      List<VehicleFenceDto> inList  = new ArrayList<>();
      List<VehicleFenceDto> outList = new ArrayList<>();
      vehicleFenceResDtos.forEach(vfr -> {
        VehicleFenceDto vehicleFenceDto = new VehicleFenceDto();
        CommonUtils.copyProperties(vfr, vehicleFenceDto);

        if(FenceAlarmTypeEnum.OUT.getCode() == vfr.getAlarmType()){
          outList.add(vehicleFenceDto);
        }else{
          inList.add(vehicleFenceDto);
        }
      });

      map.put(Constant.MAP_KEY_IN, inList);
      map.put(Constant.MAP_KEY_OUT, outList);
      return map;
    }catch (Exception e){
      log.error("查询围栏信息异常", e);
      return map;
    }
  }

  /**
   * tbox是否已授权
   * @param vin
   * @return
   */
  @Override
  public AuthDto isAuthorized(String vin){

    AuthDto authDto = AuthDto.newInstance();

    try{
      RestResponse<com.moli.iov.base.model.dto.res.AuthDto > restResponse = vehicleBaseAuthRemoteService
          .getVehicleBaseAuthByVin(vin);
      log.info("1 tbox是否已授权: {}", restResponse);
      if(restResponse != null && restResponse.flag && restResponse.getData() != null){
        com.moli.iov.base.model.dto.res.AuthDto authDtoBase = restResponse.getData();
        CommonUtils.copyProperties(authDtoBase, authDto);
        log.info("2 tbox是否已授权 authDtoBase:{}  authDto:{}", authDtoBase, authDto);
      }
    }catch(Exception e){
      log.error("tbox是否已授权 异常", e);
    }

    return authDto;
  }

  /**
   * 获取最后上报时间
   * @param vins
   * @return
   */
  @Override
  public Map<String, Date> getLastReportTimeMap(List<String> vins) {
    try {
      RestResponse<Map<String, Date>> lastReportTimeMap = realService.getLastReportTimeMap(vins);

      if(!lastReportTimeMap.flag || lastReportTimeMap.getData() == null){
        return Collections.emptyMap();
      }

      return lastReportTimeMap.getData();
    } catch (Exception e) {
      log.error("获取最后上报时间 异常", e);
      return Collections.emptyMap();
    }

  }

  /**
   * 查询所有在网车辆
   * @return
   */
  @Override
  public List<String> listVehicleBase(){
    List<VehicleBase> vehicleBases = vehicleBaseRemoteService.listVehicleBase();
    List<String> vins = new ArrayList<>();
    vehicleBases.forEach(base -> {
      if(base == null || StringUtil.isBlank(base.getVin())){
        return;
      }

      vins.add(base.getVin());
    });

    return vins;
  }

}
